package handler;

import java.util.List;

import jiyici.Constant.AuthenticateKey;
import jiyici.Constant.ErrorCode;
import jiyici.Constant.GetAction;
import models.Category;
import models.Item;
import models.User;

import org.apache.commons.lang.StringUtils;

import play.mvc.Http.Request;
import play.mvc.Result;
import util.ModelUtil;

public class GetHandler {

    public static Result handleAction(final int action, final Request request) {
        return handleAuthenticatedAction(action, request);
    }

    private static Result handleAuthenticatedAction(final int action, final Request request) {
        User user = getUserFromQueryString(request);
        if (user == null) {
            return HandlerUtil.responseError(action, ErrorCode.ERROR_NOT_AUTHENTICATED);
        }
        switch (action) {
        case GetAction.GET_ITEM:
            List<Item> items = Item.findByUser(user);
            return HandlerUtil.responseSuccess(action, ModelUtil.jsonOfItemList(items));
        case GetAction.GET_CATEGORY:
            List<Category> categories = Category.allList(user);
            return HandlerUtil.responseSuccess(action, ModelUtil.jsonOfCategoryList(categories));
        default:
            return HandlerUtil.responseError(action, ErrorCode.ERROR_ACTION_NOT_SUPPORTED);
        }
    }

    private static User getUserFromQueryString(final Request request) {
        String userIdString = request.getQueryString(AuthenticateKey.USER_ID);
        String token = request.getQueryString(AuthenticateKey.TOKEN);
        long userId = 0;
        try {
            userId = Long.parseLong(userIdString);
        } catch (Exception e) {
        }
        if (userId <= 0 || StringUtils.isBlank(token)) {
            return null;
        }
        return User.authenticateByIdToken(userId, token);
    }

}
